<template>
  <ScrollArea :bot-margin="50">
    <div class="sub-header" v-if="props.name == 'hw'">Hardware version</div>
    <div class="sub-header" v-if="props.name == 'sw'">Software version</div>
    <q-table
      class="my-table"
      :rows="parent"
      :columns="cols"
      :rows-per-page-options="[0]"
      @row-dblclick="dblclickFn"
      wrap-cells
    >
      <template v-slot:body-cell="props">
        <q-td :class="getClass(props.row)">
            {{ props.value }}
        </q-td>
      </template>

      <template v-slot:body-cell-action="props">
        <q-td :class="getClass(props.row)">
            <q-btn
              class="edit-btn"
              dense
              :disable="readOnly"
              flat
              icon="edit"
              @click="openEditDiag(props.row.repair_order_part_version_id)"
            />
        </q-td>
      </template>
    </q-table>
    <div class="sub-header" v-if="props.name == 'hw' && childs.length > 0">
      Childs Hardware version
    </div>
    <div class="sub-header" v-if="props.name == 'sw' && childs.length > 0">
      Childs Software version
    </div>
    <q-table
      v-if="childs.length > 0"
      class="my-table"
      :rows="childs"
      :columns="cols"
      :rows-per-page-options="[0]"
      @row-dblclick="dblclickFn"
      wrap-cells
    >
      <template v-slot:body-cell="props">
        <q-td :class="getClass(props.row)">
            {{ props.value }}
        </q-td>
      </template>

      <template v-slot:body-cell-action="props">
        <q-td :class="getClass(props.row)">
            <q-btn
              class="edit-btn"
              dense
              :disable="readOnly"
              flat
              icon="edit"
              @click="openEditDiag(props.row.repair_order_part_version_id)"
            />
        </q-td>
      </template>
    </q-table>
  </ScrollArea>
  <q-dialog v-model="editDiag">
    <RepairOrderPartVersionForm
      :id="editId"
      :mode="'edit'"
      :version="props.name"
      @submit="onSubmit"
      @close="onClose"
    />
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getStatusColor } from 'src/utils/getPublic';
import TabContainer from '../container/TabContainer.vue';
import { CurrentLatestVersion } from 'src/services/type';
import { getAllVersion } from 'src/services/repairService';
import RepairOrderPartVersionForm from '../repairOrderPartVersion/RepairOrderPartVersionForm.vue';
import { useVersionStore } from 'src/stores/versionStore';
import { read } from 'fs';
import ScrollArea from '../ScrollArea.vue';

const props = withDefaults(
  defineProps<{
    name: 'sw' | 'hw';
    repairOrder: number;
    editable: boolean;
    stockCode: string;
    isReadOnly: boolean;
  }>(),
  {
    editable: true,
  }
);

const readOnly = ref(false);
if (props.isReadOnly) {
  readOnly.value = true;
}

const align = 'left';
const cols = [
  {
    name: 'description',
    label: 'Short Description',
    field: 'description',
    sortable: true,
    align,
  },
  {
    name: 'serial_no',
    label: 'Serial No',
    field: 'serail_no',
    sortable: true,
    align,
  },
];

if (props.name) {
  cols.push({
    name: 'latest',
    label: 'Latest',
    field: `latest_${props.name}_ver`,
    sortable: false,
    align,
    format: (v: string[]) => {
      if (v.length == 0) {
        return '';
      }
      const arr = []
      for(let str of v){
        if (arr.indexOf(str)==-1 && str != ''){
          arr.push(str)
        }
      }
      return arr.join(',');
    },
  });
  cols.push({
    name: 'current',
    label: 'Current',
    field: `current_${props.name}_ver`,
    sortable: false,
    align,
  });
}

if (props.editable) {
  cols.push({
    name: 'action',
    label: 'Action',
    field: 'action',
    sortable: false,
    align,
  });
}

const emit = defineEmits(['update']);

const editDiag = ref(false);
const editId = ref(0);
const parent = ref<CurrentLatestVersion[]>([]);
const childs = ref<CurrentLatestVersion[]>([]);

const versionStore = useVersionStore();
versionStore.init();
function getField() {
  return props.name === 'sw' ? 'sw_ver' : 'hw_ver';
}

function getClass(item: CurrentLatestVersion) {
  //const correct = getIsCorrect(item);
  if (props.name == 'hw') {
   /*  const correct = versionStore.checkHWVersion(
      item.stock_code,
      item.current_hw_ver
    ); */

    return getStatusColor(item.hw_ver_correct ? 'pass' : 'fail');
  }
  if (props.name == 'sw') {
   /*  const correct = versionStore.checkSWVersion(
      item.stock_code,
      item.current_sw_ver
    ); */
    return getStatusColor(item.sw_ver_correct ? 'pass' : 'fail');
  }
}

function getIsCorrect(item: CurrentLatestVersion) {
  const key = (getField() + '_correct') as keyof CurrentLatestVersion;
  return item[key];
}

function getCurrentVersion(item: CurrentLatestVersion) {
  const key = ('current_' + getField()) as keyof CurrentLatestVersion;
  return item[key];
}

function getLatestVersion(item: CurrentLatestVersion) {
  const key = ('latest_' + getField()) as keyof CurrentLatestVersion;
  return item[key];
}

async function initData() {
  if (props.stockCode) {
    const res = await getAllVersion(props.repairOrder);

    const arr = res.filter((item)=>{
      console.log(item);
      
      if (props.name =='sw'){
        return item.latest_sw_ver.filter(i=>i!='N/A' && i != '').length > 0
      }
      if (props.name =='hw'){
        return item.latest_hw_ver.filter(i=>i!='N/A' && i != '').length > 0
      }
    })

    parent.value = arr.filter((item) => item.stock_code == props.stockCode)
    childs.value = arr.filter((item) => item.stock_code != props.stockCode)
  }
}

function filterFn(item:CurrentLatestVersion){

    console.log(item);
    
    if (props.name =='sw'){   
      return item.latest_sw_ver != 'N/A'
    }
    if (props.name =='hw'){
      return item.latest_hw_ver != 'N/A'
    }
  
}

function openEditDiag(id: number) {
  editId.value = id;
  editDiag.value = true;
}

function dblclickFn(evt: any, row: CurrentLatestVersion, index: number) {
  if (readOnly.value){
    return
  }
  editId.value = row.repair_order_part_version_id;
  editDiag.value = true;
}

onMounted(() => {
  initData();
});

function onSubmit() {
  initData().then(() => emit('update'));
}

function onClose() {
  editDiag.value = false;
}
</script>
<style scoped>
table {
  border-collapse: collapse;
  table-layout: fixed;
}

td {
  padding: 0.5rem;
}

table thead {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: white;
}

/* upper case */
.upper {
  text-transform: uppercase;
}
</style>
